package com.dbgs.insurance.insuredperson.activity.register;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.util.SparseArray;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.bumptech.glide.Glide;
import com.dbgs.insurance.insuredperson.R;
import com.dbgs.insurance.insuredperson.constants.ConstInt;
import com.dbgs.insurance.insuredperson.permissions.IPermission;
import com.dbgs.insurance.insuredperson.view.city.CitySelectedActivity;
import com.hss.base.BaseActivty;
import com.hss.base.util.StartActivityUtil;
import com.leon.lib.settingview.LSettingItem;
import com.lz.commonlibrary.utils.ListUtils;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import rx.Subscriber;

/**
 * Created by Administrator on 2018/5/14.
 */

public class RegisterInfoActivity extends BaseActivty implements IPermission {

    @BindView(R.id.return_img)
    AppCompatImageView returnImg;
    @BindView(R.id.name)
    AppCompatTextView name;
    @BindView(R.id.name_tv)
    AppCompatEditText nameTv;
    @BindView(R.id.sex)
    AppCompatTextView sex;
    @BindView(R.id.btn_man)
    RadioButton btnMan;
    @BindView(R.id.btn_woman)
    RadioButton btnWoman;
    @BindView(R.id.sex_rg)
    RadioGroup sexRg;
    @BindView(R.id.id_num)
    AppCompatTextView idNum;
    @BindView(R.id.id_num_tv)
    AppCompatEditText idNumTv;
    @BindView(R.id.id_card_str1)
    AppCompatTextView idCardStr1;
    @BindView(R.id.id_card_face)
    AppCompatImageView idCardFace;
    @BindView(R.id.id_card_other_side)
    AppCompatImageView idCardOtherSide;
    @BindView(R.id.select_address)
    LSettingItem selectAddress;

    public static final String EXT_OUT_IMGS = "EXT_OUT_IMGS";
    public static final int REQUEST_ID_FRONT_IMAGE = 3000;
    private int mFlag;
    private SparseArray<String> imgsArr = new SparseArray<>();
    private ArrayList<String> waitForUpoload;
    private ArrayList<String> upoloaded;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_info);
        ButterKnife.bind(this);
        initData();
        initView();
        initListener();
    }

    @Override
    public void initData() {
        super.initData();
    }

    @Override
    public void initView() {
        super.initView();
    }

    @Override
    public void initListener() {
        super.initListener();
        selectAddress.setmOnLSettingItemClick(new LSettingItem.OnLSettingItemClick() {
            @Override
            public void click(boolean isChecked) {
                StartActivityUtil.startActivityForResult(CitySelectedActivity.class, ConstInt.REQUEST_CITYSELECTEDACTIVITY_CODE, RegisterInfoActivity.this);
            }
        });

    }


    @OnClick({R.id.return_img, R.id.id_card_face_ll, R.id.id_card_other_side_ll, R.id.submit_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.return_img:
                exit();
                break;
            case R.id.id_card_face_ll:
                mFlag = 1;
                takePhoto();
                break;
            case R.id.id_card_other_side_ll:
                mFlag = 2;
                takePhoto();
                break;
            case R.id.submit_btn:
                /*if (imgsArr == null || imgsArr.size() != 2) {
                    showToast("请提交身份证正反面图片各一张");
                    return;
                }*/
                if (waitForUpoload == null) {
                    waitForUpoload = new ArrayList<>();
                } else {
                    waitForUpoload.clear();
                }
                waitForUpoload.add(imgsArr.get(0));
                waitForUpoload.add(imgsArr.get(1));

                if (upoloaded == null) {
                    upoloaded = new ArrayList<>();
                } else {
                    upoloaded.clear();
                }
                startActyForResult(RegisterSuccessActivity.class, ConstInt.REQUEST_REGISTER_CODE);
                break;
        }
    }

   /* *//**
     * 上传退出
     *//*
    private void uploadPic() {
        if (waitForUpoload.size() <= 0) {
            Intent intent = new Intent();
            intent.putStringArrayListExtra(EXT_OUT_IMGS, upoloaded);
            finishActivity(RESULT_OK, intent);
        } else {
            String dir = StrUtil.getFileDir(GlobalCache.getInstance().getUserId());
            String fileName = waitForUpoload.get(0);
            upLoadImg(dir, fileName);
        }
    }


    *//**
     * 压缩图片
     *//*
    private void upLoadImg(final String dir, final String fileName) {
        int zoom = FileUtils.getScale(fileName, ConsInt.MAX_IMAGE_SIZE);
        if (zoom < 0) {
            return;
        }
        if (zoom > 1) {
            File newFile = CompressUtil.compressImage(getApplicationContext(), fileName);
            doUpLoadImg(dir, newFile.getAbsolutePath());
        } else {
            doUpLoadImg(dir, fileName);
        }
    }

    *//**
     * 上传至服务器
     *//*
    private void doUpLoadImg(final String dir, final String fileName) {
        addSubscription(ApiManager.getInstance().getmApi()
                .uploadFileToken(ReqCreateParams.requestBaseParams(GlobalCache.getInstance().getReqBaseParams()))
                .subscribeOn(Schedulers.io())
                .map(new Func1<ResQiniuToken, String>() {
                    @Override
                    public String call(ResQiniuToken resQiniuToken) {
                        return resQiniuToken.token;
                    }
                }).flatMap(new Func1<String, Observable<ResFile>>() {
                    @Override
                    public Observable<ResFile> call(String s) {
                        return ApiManager.getInstance().getmApi()
                                .uploadFile(ReqCreateParams.uploadFileParams(s, dir, new File(fileName)));
                    }
                })

                .observeOn(AndroidSchedulers.mainThread()), new Subscriber<ResFile>() {
            @Override
            public void onCompleted() {
                hideLoadingDialog();
            }

            @Override
            public void onError(Throwable e) {
                hideLoadingDialog();
                showToast(e.getMessage());
            }

            @Override
            public void onNext(ResFile o) {
                upoloaded.add(o.file);
                waitForUpoload.remove(0);
                uploadPic();
            }

            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }
        });
    }*/

    public void takePhoto() {
        getPermission().request(Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        )
                .subscribe(new Subscriber<Boolean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {//AssessQuestionFragment
                        if (aBoolean) {
                            Intent intent = new Intent(RegisterInfoActivity.this, MultiImageSelectorActivity.class);
                            intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                            startActivityForResult(intent, RegisterInfoActivity.REQUEST_ID_FRONT_IMAGE);

                        } else {
                            showToast("请打开读写sd卡和调用相机的权限");
                        }

                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case REQUEST_ID_FRONT_IMAGE:
                if (resultCode==RESULT_OK && data!=null){
                    ArrayList<String> tmpList = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                    if (!ListUtils.isEmpty(tmpList)) {
                        if (mFlag == 1) {
                            imgsArr.put(0, tmpList.get(0));
                            Glide.with(this).load(tmpList.get(0)).centerCrop().into(idCardFace);

                        } else {
                            imgsArr.put(1, tmpList.get(0));
                            Glide.with(this).load(tmpList.get(0)).centerCrop().into(idCardOtherSide);
                        }
                    }
                }
                break;
            case ConstInt.REQUEST_CITYSELECTEDACTIVITY_CODE:
                if (resultCode==RESULT_OK && data != null) {
                    selectAddress.setLeftText(data.getStringExtra("change01"));
                }
                break;
            case ConstInt.REQUEST_REGISTER_CODE:
                if (resultCode == ConstInt.RESULT_VALUE_CHANGED){
                    setResult(resultCode);
                    exit();
                }
                break;
        }
        /*if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_ID_FRONT_IMAGE) {
                if (data != null) {
                    ArrayList<String> tmpList = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                    if (!ListUtils.isEmpty(tmpList)) {
                        if (mFlag == 1) {
                            imgsArr.put(0, tmpList.get(0));
                            Glide.with(this).load(tmpList.get(0)).centerCrop().into(idCardFace);

                        } else {
                            imgsArr.put(1, tmpList.get(0));
                            Glide.with(this).load(tmpList.get(0)).centerCrop().into(idCardOtherSide);
                        }
                    }
                }
            } else if (REQ_CITYSELECTEDACTIVITY_CODE == requestCode) {
                if (data != null) {
                    selectAddress.setLeftText(data.getStringExtra("change01"));
                }
            }
        }*/
    }

    RxPermissions rxPermissions; // where this is an Activity instance

    @Override
    public RxPermissions getPermission() {
        if (rxPermissions == null) {
            rxPermissions = new RxPermissions(this); // where this is an Activity instance
        }
        return rxPermissions;
    }
}
